package DataOperator;

import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import SearchTree.SearchTreeBuilder;

public class IDSPackager extends BasePackager {	
	static final String IndexFilePath = "Out/Index";
	static final String DictFilePath = "Out/Dict";
	static final String SoundFilePath = "Out/Sound";
	static final String ListFilePath = "Out/WordList.txt";
	static final String LogFilePath = "Out/Log.txt";
	
	private DataOutputStream dstDictWriter = null;
	
	public ArrayList<String> words = new ArrayList<String>();
	public HashMap<String, WordBuildInfo> dict = new HashMap<String, WordBuildInfo>();
	
	private SearchTreeBuilder searchBuilder = new SearchTreeBuilder();
	private SoundPackager soundPackager = new SoundPackager();
	private BufferedWriter wordListBuilder = null;
	
	public ArrayList<String> noTransWords = new ArrayList<String>();
	public ArrayList<String> noSoundWords = new ArrayList<String>();
	
	// Override
	protected void Init(){
		try{
			dstDictWriter = new DataOutputStream(new FileOutputStream(DictFilePath));
			wordListBuilder = new BufferedWriter(new FileWriter(ListFilePath));
		}
		catch(IOException e){
			e.printStackTrace();
		}
	}
	
	protected void BeforeBuild() throws IOException{
		super.BeforeBuild();
		soundPackager.Init();
	}
	
	protected void AfterBuild(){
		super.AfterBuild();
		searchBuilder.BuildIndex(IndexFilePath);
	}
	
	public void PrepareWord(String word, WordBuildInfo wordInfo) throws IOException{
	}
	
	public void BuildWord(String word, WordBuildInfo info) throws IOException{
		if(info.offset == -1){
			info.offset = dstDictWriter.size();;
			if(!soundPackager.PackWordSound(word, info)){
				noSoundWords.add(info.word);
			}
			info.Build(dstDictWriter);
			info.length = dstDictWriter.size() - info.offset;	
		}
		searchBuilder.AddItem(word, info.offset, info.length);
		wordListBuilder.write(word + "\r\n");
		wordListBuilder.flush();
	}
}
